package com.whfc.common.third.mas.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.third.mas.MasProperties;
import com.whfc.common.third.mas.MasRadarApi;
import com.whfc.common.third.mas.entity.MonitorListRequest;
import com.whfc.common.third.mas.entity.MonitorListResponse;
import com.whfc.common.third.mas.entity.RadarProjectListRequest;
import com.whfc.common.third.mas.entity.RadarProjectListResponse;
import com.whfc.common.third.mas.entity.RadarStatusResponse;
import com.whfc.common.util.HttpUtil;

import cn.jiguang.common.utils.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * MAS雷达相关API实现
 */
@Service
public class MasRadarApiImpl implements MasRadarApi {

    private static final Logger logger = LoggerFactory.getLogger(MasRadarApiImpl.class);

    @Autowired
    private MasProperties masProperties;

    private static final String MONITOR_LIST_URL = "/API/mas/v3/monitor/list";

    @Override
    public RadarProjectListResponse getRadarProjectList(RadarProjectListRequest request, String satoken) {
        logger.info("调用MAS雷达项目列表接口，请求参数：{}", JSON.toJSONString(request));

        // 参数校验
        if (request == null) {
            throw new BizException(ResultEnum.PARAM_ERROR);
        }
        if (satoken == null || satoken.isEmpty()) {
            throw new BizException(ResultEnum.AUTHC_ERROR);
        }

        try {
            // 构建请求URL
            String url = masProperties.getApiUrl() + "/API/mas/radar/v3/radarProject/list";

            // 设置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Satoken", satoken);

            // 发送POST请求
            String response = HttpUtil.doPost(url, JSON.toJSONString(request), headers,
                    masProperties.getReadTimeout(), masProperties.getConnectTimeout());

            logger.info("调用MAS雷达项目列表接口，响应结果：{}", response);

            // 解析响应
            RadarProjectListResponse result = JSON.parseObject(response, RadarProjectListResponse.class);

            // 校验响应状态
            if (result == null) {
                logger.error("MAS雷达项目列表接口响应为空");
                throw new BizException(ResultEnum.NETWORK_ERROR);
            }

            if (result.getCode() == null || result.getCode() != 200) {
                logger.error("MAS雷达项目列表接口调用失败，错误码：{}", result.getCode());
                throw new BizException(ResultEnum.NETWORK_ERROR.getCode(),
                        "MAS雷达项目列表接口调用失败：" + result.getMsg());
            }

            return result;
        } catch (BizException e) {
            throw e;
        } catch (Exception e) {
            logger.error("调用MAS雷达项目列表接口异常", e);
            throw new BizException(ResultEnum.NETWORK_ERROR);
        }
    }

    @Override
    public RadarStatusResponse getRadarStatus(String radarNo, String satoken) {
        logger.info("调用MAS雷达状态查询接口，雷达编号：{}", radarNo);

        // 参数校验
        if (radarNo == null || radarNo.isEmpty()) {
            throw new BizException(ResultEnum.PARAM_ERROR, "雷达编号不能为空");
        }
        if (satoken == null || satoken.isEmpty()) {
            throw new BizException(ResultEnum.AUTHC_ERROR);
        }

        try {
            // 构建请求URL
            String url = masProperties.getApiUrl() + "/API/mas/open-api/radar/radar-status/get";

            // 设置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Satoken", satoken);

            // 设置查询参数
            Map<String, String> params = new HashMap<>();
            params.put("radarNo", radarNo);

            // 发送GET请求
            String response = HttpUtil.doGet(url, params, headers,
                    masProperties.getReadTimeout(), masProperties.getConnectTimeout());

            logger.info("调用MAS雷达状态查询接口，响应结果：{}", response);

            // 解析响应
            RadarStatusResponse result = JSON.parseObject(response, RadarStatusResponse.class);

            // 校验响应状态
            if (result == null) {
                logger.error("MAS雷达状态查询接口响应为空");
                throw new BizException(ResultEnum.NETWORK_ERROR);
            }

            if (result.getCode() == null || result.getCode() != 200) {
                logger.error("MAS雷达状态查询接口调用失败，错误码：{}", result.getCode());
                throw new BizException(ResultEnum.NETWORK_ERROR.getCode(),
                        "MAS雷达状态查询接口调用失败：" + result.getMsg());
            }

            return result;
        } catch (BizException e) {
            throw e;
        } catch (Exception e) {
            logger.error("调用MAS雷达状态查询接口异常", e);
            throw new BizException(ResultEnum.NETWORK_ERROR);
        }
    }

    @Override
    public MonitorListResponse getMonitorList(MonitorListRequest request, String satoken) throws BizException {
        logger.info("获取监控数据列表请求参数: {}", JSON.toJSONString(request));
        
        // 参数校验
        if (request == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "请求参数不能为空");
        }
        if (StringUtils.isEmpty(satoken)) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "satoken不能为空");
        }
        if (request.getCurrent() == null || request.getCurrent() <= 0) {
            request.setCurrent(1);
        }
        if (request.getSize() == null || request.getSize() <= 0) {
            request.setSize(10);
        }
        
        try {
            // 构建完整URL
            String url = masProperties.getApiUrl() + MONITOR_LIST_URL;
            
            // 设置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("satoken", satoken);
            headers.put("Content-Type", "application/json");
            
            // 发送POST请求
            String response = HttpUtil.doPost(url, JSON.toJSONString(request), headers, 
                masProperties.getReadTimeout(), masProperties.getConnectTimeout());
            
            logger.info("获取监控数据列表响应: {}", response);
            
            // 响应为空处理
            if (StringUtils.isEmpty(response)) {
                throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), "获取监控数据列表响应为空");
            }
            
            // 解析响应结果
            JSONObject resultJson = JSONObject.parseObject(response);
            
            // 检查响应状态
            if (resultJson == null) {
                throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), "获取监控数据列表响应解析失败");
            }
            
            // 转换为实体类
            return JSON.toJavaObject(resultJson, MonitorListResponse.class);
        } catch (BizException e) {
            // 直接抛出业务异常
            throw e;
        } catch (Exception e) {
            logger.error("获取监控数据列表失败: {}", e.getMessage(), e);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), "获取监控数据列表失败: " + e.getMessage());
        }
    }
}